
package org.vectrics.skill.struts;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.ecs.html.IMG;
import org.apache.ecs.html.Input;
import org.apache.log4j.Category;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Form;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.web.tags.SkillGui;
import org.vectrics.skill.Skill;
import org.vectrics.skill.SkillException;
import org.vectrics.skill.SkillRating;
import org.vectrics.skill.SkillRatingSet;
import org.vectrics.skill.SkillScoringMethod;
import org.vectrics.skill.SkillSetUtil;
import org.vectrics.struts.VectricsTagSupport;


abstract public class ShowSkillsTagAbstract extends VectricsTagSupport {

	private static final long serialVersionUID = 8787799442675606200L;

	private static Category log = Category.getInstance(ShowSkillsTagAbstract.class);
    public static String ENTRY_TYPE_PARAM = "entry_type";
    public static String EDIT_PARAM = "edit_skills";
    public static String JOB_PARAM = "job";
    private boolean editMode = false;
    

    public ShowSkillsTagAbstract() {
    }

    abstract protected SkillRatingSet getSkillRatingSet() throws SkillException;
    abstract protected boolean getShowSkillDetails();
    
   	public String makeStartTag()  {
   		log.debug("doStartTag() called");
   		HttpServletRequest request = (HttpServletRequest)super.pageContext.getRequest();
   		String contextPath = request.getContextPath();
   		
   		Skill rootSkill = null;
		rootSkill = RecruitServiceLocator.getSkillProvider().getRootSkill();
   		
   		
        String entryTypeParam = request.getParameter(ENTRY_TYPE_PARAM);
        String editParam = request.getParameter(EDIT_PARAM);
        if ((editParam != null) && (editParam.startsWith("true"))) {
            editMode = true;
        }

        SkillRatingSet owner = null;        
        String jobId = request.getParameter(JOB_PARAM);
        
        try {
        	owner = getSkillRatingSet();
        }
        catch (SkillException se) {
        	log.error("Exception finding the skillRatingSet while displaying skill summary", se);
        	throw new SystemException("Exception finding the skillRatingSet while displaying skill summary", se);
        }
            
        
        log.debug("doRender() - geting content for skills table.");
        
        StringBuffer html = new StringBuffer();
        html.append("<br>");
        if (editMode) {
            Form form = new Form();
            form.setMethod("post");
            form.addHidden("action", SaveSkillsActionAbstract.ACTION_NAME);
            form.addHidden("save", "true");
            
            form.setAction("/recruit/main/user/skill");
            form.addElement(getSkillTable(rootSkill, owner, request));
            

            form.addElement("<br>");
            Input input = new Input();
            input.setType(Input.SUBMIT);
            input.setStyle("width:90;height=" +
            		"18;font-family:verdana,arial,sans serif;font-size=" +
            		"11px");        
            input.setName("next_btn");
            input.setValue("Next");
            form.addElement(input);
            
            html.append(form.toString());
        }
        else {
            html.append(getSkillTable(rootSkill, owner, request));
        }
        
        return(html.toString());
        
   	}
    
    /**
     * 
     * @param rootSkill
     * @param owner
     * @param request
     * @return
     */    
    public Table getSkillTable(Skill rootSkill, SkillRatingSet owner, HttpServletRequest request) {        
        log.debug("Building skill summary table");
        BorderTable table = new BorderTable();

        table.setCellSpacing(0);
        table.setWidth("700");

        Row row1 = table.addRow();
        row1.setBgColor("#003040");
        row1.setDefaultBgImage(this.getContextPath() + "/site-graphics/tbl_hdr.gif");
        
		
        Cell cell2 = row1.addCell();
        cell2.setClass("tableHdrBg");
        cell2.addElement(TextHelper.getFont("tableHdrFont", "Description"));

        Cell cell3 = row1.addCell();
        cell3.setClass("tableHdrBg");
        cell3.addElement(TextHelper.getFont("tableHdrFont", "Rating"));

        SkillSetUtil util = new SkillSetUtil(owner, rootSkill);
        log.debug("getSkillTable(), clearing implied skills");
        util.clearImpliedParentSkills();
        log.debug("getSkillTable(), clearing unrated skills");
        util.clearUnrated();
        log.debug("getSkillTable(), showing skills");
        showSkills(rootSkill, owner, rootSkill, table, 0);

        /*
        Iterator iter = userProfile.getSeekerInfo().getUserSkillSet().iterator();
        while (iter.hasNext()) {
            SkillRating rating = (SkillRating)iter.next();

            Row row2 = table.addRow();
            Cell categoryCell = row2.addCell();
            Cell descCell = row2.addCell();
            Cell ratingCell = row2.addCell();


            String categoryText = "";
            if (rating.getSkill().getParent() != null) {
                categoryText = rating.getSkill().getParent()
                        .getDescription();
            }
            else {
                categoryText = "Error looking up category";
            };

            categoryCell.addElement(TextHelper.getFont("stdFont", categoryText));
            descCell.addElement(TextHelper.getFont("stdFont", rating.getSkill().getDescription()));
            ratingCell.addElement(TextHelper.getFont("stdFont", rating.getDescription()));
        };
        */
        return(table);
    };


    void showSkills(Skill rootSkill, SkillRatingSet owner, Skill parent, 
				Table table, int indent) {

        if (log.isDebugEnabled())
            log.debug("showSkills()  parent: " + parent.getCode());
        Iterator iter = parent.getChildren().iterator();
        while (iter.hasNext()) {
            Skill childSkill = (Skill)iter.next();
            showSkill(rootSkill, owner, childSkill, table, indent);
            SkillSetUtil util = new SkillSetUtil(owner, rootSkill);
            if (util.hasSkillRatingInBranch(childSkill)) {
                showSkills(rootSkill, owner, childSkill, table, indent + 1);
            }
        }
        
    }
    
    void showSkill(Skill rootSkill, SkillRatingSet owner, Skill skill, Table table, 
			int indent) {
    	
        if (log.isDebugEnabled())
            log.debug("showSkill() called.  Skill = " + skill.getCode());

        if (owner == null) {
        	log.error("Invalid parameter passed to showSkill() - owner was NULL");
        	throw new SystemException("Invalid parameter passed to showSkill() - owner was NULL");
        }
		if (rootSkill == null) {
        	log.error("Invalid parameter passed to showSkill() - rootSkill was NULL");
        	throw new SystemException("Invalid parameter passed to showSkill() - rootSkill was NULL");
		}
		if (skill == null) {
        	log.error("Invalid parameter passed to showSkill() - skill was NULL");
        	throw new SystemException("Invalid parameter passed to showSkill() - skill was NULL");
		}
        SkillRating rating = owner.findSkillRating(skill);
        log.debug("showSkill() - making row for skill");
        Row row2 = table.addRow();
        //Cell categoryCell = row2.addCell();
        Cell descCell = row2.addCell();
        Cell ratingCell = row2.addCell();

        Table descTable = new Table();
        descTable.setCellPadding(0);
        descTable.setCellSpacing(0);
        descTable.setBorder(0);
        Row descRow = descTable.addRow();
        

        log.debug("showSkill() - building indention for skill rating on hierarchy.");
        for (int i = 0; i < indent; i++) {
            Cell indentCell = descRow.addCell();
            indentCell.addElement(makeIndentImage());
        }
        
        IMG img = new IMG();
        img.setSrc("/recruit/graphics/check_sml.gif");
        img.setAlt("");
        img.setBorder(0);
        img.setHeight(12);
        img.setWidth(12);
       
        if (rating == null) {
           SkillSetUtil util = new SkillSetUtil(owner, rootSkill);
           if (util.hasSkillRatingInBranch(skill) == false) {
               img.setSrc("/recruit/graphics/x_sml.gif");
           }
        }
               
        descRow.addCell().addElement(img);


        log.debug("showSkill() - adding skill desc to cell.");
        //categoryCell.addElement(TextHelper.getFont("stdFont", indentStr); //categoryText));
        descRow.addCell().addElement(TextHelper.getFont("subFont", skill.getDescription()));
        descCell.addElement(descTable);
        
        log.debug("showSkill() - adding skill rating description to cell.");
        if (rating == null) {
            ratingCell.addElement(TextHelper.getFont("stdFont", "&nbsp;"));
        } else {
            if (editMode == true) {
                if (getShowSkillDetails()) {
                    if (skill.getScoringMethod().getCode().equals(SkillScoringMethod.SCORING_METHOD_LEVEL))
                        ratingCell.addElement(SkillGui.makeSkillLevelTable(rating, skill));
                    //else if (skill.getScoringMethod().getCode().equals(Skill.SCORING_METHOD_YEARS))
                    //    SkillGui.displayYears(rating, skill, ratingCell);
                    else if (skill.getScoringMethod().getCode().equals(SkillScoringMethod.SCORING_METHOD_YES_NO))
                        SkillGui.displayYesNo(rating, skill, ratingCell);
                    else 
                    	throw new SystemException("Do not know how to handle: " + skill.getScoringMethod().getCode());
                }
                else {
                    ratingCell.addElement(SkillGui.makeSkillLevelTable(rating, skill));
                }
                
            }
            else {
                ratingCell.addElement(TextHelper.getFont("subFont", this.getPhrase(rating.getDescription())));
            }
            ratingCell.addElement("&nbsp;");
        }
        log.debug("showSkill() - done.");
    }
    
    
    private IMG makeIndentImage() {
        
       IMG img = new IMG();
       img.setSrc("/recruit/graphics/cleardot.gif");
       img.setAlt("");
       img.setBorder(0);
       img.setHeight(10);
       img.setWidth(10);
       return(img);
    }

}